<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据加载状态
const tableLoading = ref(false);

// 消息列表数据
const messageList = ref([]);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  status: '',
  dateRange: []
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 消息类型选项
const messageTypeOptions = [
  { label: '系统通知', value: 'system' },
  { label: '活动通知', value: 'activity' },
  { label: '优惠通知', value: 'discount' },
  { label: '会员通知', value: 'member' },
  { label: '订单通知', value: 'order' }
];

// 消息状态选项
const messageStatusOptions = [
  { label: '待发送', value: 'pending' },
  { label: '发送中', value: 'sending' },
  { label: '已发送', value: 'sent' },
  { label: '已读', value: 'read' },
  { label: '发送失败', value: 'failed' }
];

// 加载消息数据
const loadMessageData = () => {
  tableLoading.value = true;
  
  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据
    messageList.value = Array.from({ length: 20 }, (_, index) => {
      const id = 'MSG' + (100000 + index).toString();
      const typeIndex = Math.floor(Math.random() * 5);
      const statusIndex = Math.floor(Math.random() * 5);
      const now = new Date();
      const createTime = new Date(now.getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000);
      const sendTime = statusIndex > 0 ? new Date(createTime.getTime() + Math.floor(Math.random() * 24) * 60 * 60 * 1000) : null;
      const readTime = statusIndex === 3 ? new Date(sendTime.getTime() + Math.floor(Math.random() * 24) * 60 * 60 * 1000) : null;
      
      // 消息标题
      const titles = [
        '系统维护通知',
        '周末活动预告',
        '会员积分更新',
        '优惠券到期提醒',
        '新活动上线通知',
        '充值优惠活动',
        '会员等级升级提醒',
        '订单状态更新'
      ];
      const title = titles[Math.floor(Math.random() * titles.length)];
      
      // 随机目标会员数
      const targetCount = Math.floor(Math.random() * 500) + 1;
      
      // 随机成功发送数
      const sentCount = statusIndex >= 2 ? Math.floor(targetCount * (0.9 + Math.random() * 0.1)) : 0;
      
      // 随机消息内容
      const contents = [
        '尊敬的会员，系统将于本周六进行维护升级，届时将暂停服务2小时，请提前安排您的行程。',
        '本周末将举办棋牌大赛，参与即可获得积分奖励，前三名还有现金大奖！',
        '您的会员积分已更新，可在会员中心查看详情。',
        '您有优惠券即将到期，请尽快使用。',
        '新的团购活动已上线，限时特惠，先到先得！',
        '充值优惠活动开始了，充值满500元送100元，名额有限！',
        '恭喜您的会员等级已升级，可享受更多优惠权益。',
        '您的订单状态已更新，请查看详情。'
      ];
      const content = contents[Math.floor(Math.random() * contents.length)];
      
      return {
        id,
        messageNo: id,
        title,
        content,
        type: messageTypeOptions[typeIndex].value,
        typeName: messageTypeOptions[typeIndex].label,
        status: messageStatusOptions[statusIndex].value,
        statusName: messageStatusOptions[statusIndex].label,
        targetCount,
        sentCount,
        readCount: statusIndex === 3 ? Math.floor(sentCount * (0.3 + Math.random() * 0.5)) : 0,
        createTime: createTime.toLocaleString(),
        sendTime: sendTime ? sendTime.toLocaleString() : '--',
        readTime: readTime ? readTime.toLocaleString() : '--',
        creator: '管理员' + Math.floor(Math.random() * 5 + 1)
      };
    });
    
    pagination.total = 142; // 模拟总数据量
    tableLoading.value = false;
  }, 1000);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadMessageData();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadMessageData();
};

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1;
  loadMessageData();
};

// 重置查询条件
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.type = '';
  searchForm.status = '';
  searchForm.dateRange = [];
  
  pagination.currentPage = 1;
  loadMessageData();
};

// 查看消息详情
const viewMessageDetails = (row) => {
  ElMessage.info(`查看消息详情：${row.title}`);
};

// 发送消息
const sendMessage = (row) => {
  if (row.status !== 'pending') {
    ElMessage.warning('只能发送待发送状态的消息');
    return;
  }
  
  ElMessageBox.confirm(`确定要发送消息"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('发送成功');
    row.status = 'sent';
    row.statusName = '已发送';
    row.sendTime = new Date().toLocaleString();
    row.sentCount = row.targetCount;
  }).catch(() => {});
};

// 撤回消息
const revokeMessage = (row) => {
  if (row.status !== 'sent') {
    ElMessage.warning('只能撤回已发送的消息');
    return;
  }
  
  ElMessageBox.confirm(`确定要撤回消息"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('撤回成功');
    row.status = 'pending';
    row.statusName = '待发送';
  }).catch(() => {});
};

// 删除消息
const deleteMessage = (row) => {
  ElMessageBox.confirm(`确定要删除消息"${row.title}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功');
    loadMessageData();
  }).catch(() => {});
};

// 新建消息
const createMessage = () => {
  ElMessage.info('打开新建消息表单');
};

// 消息模板管理
const manageMessageTemplates = () => {
  ElMessage.info('打开消息模板管理页面');
};

// 消息统计
const messageStatistics = ref({
  total: 1265,
  today: 42,
  pending: 18,
  sent: 1182,
  read: 743,
  readRate: '62.9%'
});

// 初始化加载
onMounted(() => {
  loadMessageData();
});
</script>

<template>
  <div class="message-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>消息通知</h2>
    </div>
    
    <!-- 消息统计卡片 -->
    <el-row :gutter="20" class="stat-row">
      <el-col :xs="24" :sm="8" :md="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">消息总数</div>
          <div class="stat-value">{{ messageStatistics.total }}</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">今日发送</div>
          <div class="stat-value">{{ messageStatistics.today }}</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">待发送</div>
          <div class="stat-value">{{ messageStatistics.pending }}</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">已发送</div>
          <div class="stat-value">{{ messageStatistics.sent }}</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">已读数</div>
          <div class="stat-value">{{ messageStatistics.read }}</div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="8" :md="4">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-title">阅读率</div>
          <div class="stat-value">{{ messageStatistics.readRate }}</div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="消息标题/内容"
            clearable
          />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option 
              v-for="item in messageTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option 
              v-for="item in messageStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>消息列表</span>
          <div>
            <el-button type="warning" @click="manageMessageTemplates">
              <el-icon><Files /></el-icon>
              消息模板
            </el-button>
            <el-button type="primary" @click="createMessage">
              <el-icon><Plus /></el-icon>
              新建消息
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="messageList" 
        v-loading="tableLoading" 
        border 
        style="width: 100%"
      >
        <el-table-column prop="messageNo" label="消息编号" width="100" />
        <el-table-column prop="title" label="消息标题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="typeName" label="消息类型" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.type === 'system' ? 'danger' : 
                row.type === 'activity' ? 'success' : 
                row.type === 'discount' ? 'warning' : 
                row.type === 'member' ? 'primary' : 'info'
              "
            >
              {{ row.typeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发送情况" width="160">
          <template #default="{ row }">
            <div>目标: {{ row.targetCount }}人</div>
            <div>已发: {{ row.sentCount }}人</div>
            <div>已读: {{ row.readCount }}人</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.status === 'pending' ? 'info' : 
                row.status === 'sending' ? 'warning' : 
                row.status === 'sent' ? 'success' : 
                row.status === 'read' ? 'primary' : 'danger'
              "
            >
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column prop="sendTime" label="发送时间" width="150" />
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewMessageDetails(row)"
            >
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              size="small" 
              type="primary" 
              @click="sendMessage(row)"
            >
              发送
            </el-button>
            <el-button 
              v-if="row.status === 'sent'"
              size="small" 
              type="warning" 
              @click="revokeMessage(row)"
            >
              撤回
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteMessage(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.message-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.stat-row {
  margin-bottom: 20px;
}
.stat-card {
  text-align: center;
  padding: 15px 10px;
  height: 100%;
}
.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
</style> 
